<template>
	<div class="e-writing">
		 <headNav title="写邮件"></headNav>
			<group>
				 <cell @click.native="toSelectSend" title="收件人" value-align="right" is-link>
					 <div class="writing-in">
						<span v-for="(item,index) in sendUser" :key="index">{{item.name}}，</span>
					</div>
				 </cell>
				 <cell @click.native="toSelectCopy" title="抄送人" value-align="right" is-link>
					<div class="writing-in" >
						<span v-for="(item,index) in copyUser" :key="index">{{item.name}}，</span>
					</div>
				 </cell>
				<x-textarea title="主题" :max="100" v-model="emailTitle"  placeholder=""></x-textarea>
				<!-- <x-textarea title="内容"  v-model="emailContent"  placeholder=""></x-textarea> -->
				<div style="border-bottom: 1px solid #ddd;"></div>
				<vue-html5-editor :content="emailContent" :height="200"  style="border:none;"
                        @change="updateEmailContent" ></vue-html5-editor> 
				<selector placeholder="请邮件类型" v-model="emailType" title="类型" :options="emailTypeList" ></selector>
				
			</group>		
			<div class="fj-p">
				<div class="fj-label">附件</div>
				<div class="fj-val">
					<div v-for="(item,index) in fileList" :key="index" class="fj-item">
						<img class="fj-img" :src="item.fileUrl | imgUrl">
						<a @touchend="removeFile(item)" class="s-c"></a>
					</div>
					<div v-show="!uploading" class="file-input-p">
						<a class="sc-tp">上传图片</a>
						<input id="fileInput" @change="uploadFile" type="file" multiple accept="image/*"  class="file-input">
					</div>
					<div v-show="uploading" class="file-input-p">
						<load-more :tip="'正在上传...'"></load-more>
					</div>
				</div>
			</div>
			
			<x-button @click.native="sendEmail(2)" type="primary">发送</x-button>
			<x-button @click.native="sendEmail(1)" >存为草稿</x-button>
			<div class="bottom-space"></div>
		</div>
</template>
<script>
import { XTextarea, Group, XInput, Selector, Cell, XButton, LoadMore } from 'vux'
import {uploadFile, addEmail} from '@/api/emailApi'
import {mapGetters} from 'vuex'
import headNav from '@/components/headNav/headNav';


import 'font-awesome/css/font-awesome.min.css'
import initRichText from '@/util/initHTMLEditor'
initRichText()

export default {
	name: 'writeEmail',
	components: {
		 XTextarea,  
    Group,
	XInput,
	Selector,
	Cell,
	XButton,
	LoadMore,
	headNav
	},
	computed: {
		...mapGetters(['cookiesObj'])
	},
	data () {
		return {
			emailId: '',
			sendUser: [],
			copyUser: [],
			emailTypeList: [],
			emailType: '',
			emailTitle: '',
			emailContent: '输入邮件内容...',
			fileList: [],

			status: '',
			uploading: false
		}
	},
	methods: {
		toSelectSend () {
			this.$store.state.email.selectType = 1
			this.$store.state.email.selectedMan = this.sendUser
			this.$router.push('man')
		},
		toSelectCopy () {
			this.$store.state.email.selectType = 2
			this.$store.state.email.selectedMan = this.copyUser
			this.$router.push('man')
		},
		uploadFile (e) {
			var fileList = e.target.files
			for (let i = 0; i < fileList.length; i++) {
				var file = fileList[i]
				const formData = new FormData()
			formData.append('file', file)
				this.uploading = true
				uploadFile(formData).then(d => {
					if (i == fileList.length - 1) {
						document.getElementById('fileInput').value = ''
					}
					this.uploading = false
					d = JSON.parse(d)
					if (d.Code == '200') {
						this.fileList.push(d.Data)
						console.log(this.fileList)
					} else {
						this.$vux.toast.text(d.Msg, 'top')
					}	
				})
			}
		},
		removeFile (file) {
			for (var i = 0; i < this.fileList.length; i++) {
				if (file.fileUrl == this.fileList[i].fileUrl) {
					this.fileList.splice(i, 1)
				}
			}
		},
		getParam () {
			var param = {
				userId: this.cookiesObj.loginUserId,
				fileSize: 0,
				suffix: 0
			}
			if (this.emailId) {
				param.emailId = this.emailId
			}
			if (this.sendUser.length == 0) {
				this.$vux.toast.text('请选择收件人', 'top')
				return null
			} else {
				param.mainUserIds = this.sendUser.map(item => item.loginUserId).join()
			}
			if (this.copyUser.length == 0) {
				
			} else {
				// for (var i = 0; i < this.copyUser.length; i++) {
				// 	for (var u of this.sendUser) {
				// 		if (this.copyUser[i].Id == u.Id) {
				// 			this.copyUser.splice(i, 1)
				// 		}
				// 	}
				// }
				param.copyUserIds = this.copyUser.map(item => item.loginUserId).join()
			}
			if (!this.emailTitle) {
				this.$vux.toast.text('请输入主题', 'top')
				return null
			} else {
				param.title = this.emailTitle
			}
			if (!this.emailContent) {
				this.$vux.toast.text('请输入内容', 'top')
				return null
			} else {
				param.content = encodeURI(this.emailContent)
			}
			
			if (this.emailType === '') {
				this.$vux.toast.text('请选择类型', 'top')
				return null
			} else {
				param.mailTypeCode = this.emailType
			}

			if (this.fileList.length > 0) {
				param.fileNameList = this.fileList.map(item => item.fileName).join()
				param.fileValueLIst = this.fileList.map(item => item.fileUrl).join()
			}
			return param
		},
		sendEmail (status) {
			this.status = status
			var param = this.getParam()
			if (!param) {
				return
			}
			param.status = status
			console.log(param)
			addEmail({
				data: JSON.stringify(param)
			}).then(res => {
				res = JSON.parse(res)
				if (res.Code == 200) {
					this.clearData()
					if (this.status == 1) {
						this.$vux.toast.text('已保存为草稿', 'top')
						this.$store.state.email.addType = 'draft'
					} else if (this.status == 2) {
						this.$vux.toast.text('发送成功', 'top')
						this.$store.state.email.addType = 'send'
					}
					
					this.$router.go(-1)
				} else {
					this.$vux.toast.text(res.Msg, 'top')
				}
			})
		},
		clearData () {
			this.uploading = false
			this.emailId = ''
			this.sendUser = []
			this.copyUser = []
			// this.emailTypeList = []
			this.emailType = ''
			this.emailTitle = ''
			this.emailContent = ''
			this.fileList = []

			this.$store.state.email.selectedMan = []
		},
		baseHtml (email) {
			var html = ''
			html = '<p>&nbsp;</p><p>&nbsp;</p>'
			html += '<p><br />----------原始邮件----------<br />发件人：' + email.FromUserName
			html += ';<br />发送时间：' + email.SendingTime
			html += ';<br />收件人：' + email.ToEmailName
			html += ';<br />抄送：' + email.CopyEmailName
			html += ';<br />主题：' + email.Theme
			html += ';<br />内容：<br /><br />' + email.Content
			html += '</p>'
			return html
		},
		initData (emailData) {
			// 				Content: "发放水电费是发斯蒂芬暗室逢灯"
// CopyEmailId: "0a015a03bcee4defaf69ccbb5c670a9f,0dc7d5f1ddd0406fb8160a44bda2d35a"
// CopyEmailName: "刘四,刘一"
// FromUserId: "9158b144b79f4b30b32648e351c809c5"
// FromUserName: "学校管理员"
// Id: "a014b63f82194eef91faa65041f758c7"
// MailTypeCode: "0"
// SendingTime: "2019/10/12 11:47:21"
// Status: 2
// Theme: "测试详情"
// ToEmailId: "d81d7cc3ec5a417296666a2040e2d218,9c1d75d51c5040dfbfafc32d73397abd"
// ToEmailName: "郑榆,陈超"
			if (emailData) {
				if (emailData.type == 'reply') {
					this.sendUser = [{loginUserId: emailData.email.FromUserId, name: emailData.email.FromUserName}]
					this.emailTitle = '回复：' + emailData.email.Theme
					this.emailContent = this.baseHtml(emailData.email)
				} else if (emailData.type == 'transmit') {
					this.emailTitle = '转发：' + emailData.email.Theme
					this.emailContent = this.baseHtml(emailData.email)
					this.emailType = emailData.email.MailTypeCode
					this.fileList = emailData.fileList.map(item => {
						return {fileUrl: item.url, fileName: item.name}
					})
				} else if (emailData.type == 'edit') {
					this.emailId = emailData.email.Id
					var ids = emailData.email.ToEmailId.split(',')
					var names = emailData.email.ToEmailName.split(',')
					for (var i = 0; i < ids.length; i++) {
						if (ids[i]) {
							this.sendUser.push({loginUserId: ids[i], name: names[i]})
						}
					}

					ids = emailData.email.CopyEmailId.split(',')
					names = emailData.email.CopyEmailName.split(',')
					for (i = 0; i < ids.length; i++) {
						if (ids[i]) {
							this.copyUser.push({loginUserId: ids[i], name: names[i]})
						}		
					}
					
					this.emailTitle = emailData.email.Theme
					this.emailContent = emailData.email.Content
					this.emailType = emailData.email.MailTypeCode
					this.fileList = emailData.fileList.map(item => {
						return {fileUrl: item.url, fileName: item.name}
					})
				}
				
				this.$store.state.email.emailData = null
			}
		},
		updateEmailContent (e = '') {  
            this.emailContent = e
            console.info(e)
        } 
	},
	created () {
        
    },
	mounted () {
		console.log('write mounted...')

		this.$store.dispatch('email/getEmailType').then(d => {
			console.log(d)
			for (var item of d) {
				item.key = item.Id
				item.value = item.Name
			}
			this.emailTypeList = d
		})
	},
	deactivated () {
		
	},
	activated () {
		 this.setTitle('写邮件')
		 if (!this.$store.state.email.selectType) {
			 this.clearData()
		}
		switch (this.$store.state.email.selectType) {
			case 1:
				this.sendUser = this.$store.state.email.selectedMan
				this.$store.state.email.selectType = null
				break
			case 2:
				this.copyUser = this.$store.state.email.selectedMan
				this.$store.state.email.selectType = null
				break
		}
		
		this.initData(this.$store.state.email.emailData)
	}
}
</script>
<style scoped src="./css/e-mail.css"></style>

<style scoped>
.file-input-p{
	position: relative;
	clear: both;
}
.file-input{
	position: absolute;
    top: 0;
    left: 0;
	height: 100%;
	opacity: 0;
}
.fj-p{
	padding: 0.4rem 0.2rem;
	font-size: 0.3rem;
}
.fj-label{
	width: 1rem;
	display: inline-block;
	vertical-align: middle;
}
.fj-val{
	width: 5rem;
	display: inline-block;
	vertical-align: middle;
}
.fj-item{
	float: left;
	position: relative;
	margin: 0 0.5rem 0.5rem 0;
	width: 1.5rem;
	height: 1.5rem;
	text-align: center;
	background: #fff;
	box-shadow: 0 0 10px 0 rgba(0,0,0,0.5);
	font-size: 0;
}
.fj-item::before{
	content: "";
	display: inline-block;
	height: 100%;
	vertical-align: middle;
}
.fj-img{
	max-width: 100%;
	max-height: 100%;
	display: inline-block;
	vertical-align: middle;
}
.sc-tp{
	border: 1px solid #128FEF;
	color: #128FEF;
	padding: 0.1rem 0.2rem;
	border-radius: 0.1rem;
}
</style>
